package com.example.homeworkmanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.homeworkmanagement.mapper.ClassesMapper;
import com.example.homeworkmanagement.pojo.Classes;
import com.example.homeworkmanagement.pojo.Courses;
import com.example.homeworkmanagement.pojo.Majors;
import com.example.homeworkmanagement.mapper.MajorsMapper;
import com.example.homeworkmanagement.service.MajorsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.homeworkmanagement.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 拒绝加班
 * @since 2025-05-25
 */
@Service
public class MajorsServiceImpl extends ServiceImpl<MajorsMapper, Majors> implements MajorsService {
    @Autowired
    private ClassesMapper classesMapper;
    @Override
    public ResultVO<List<Majors>> getMajorList() {
        try {
            List<Majors> majorsList = this.list();
            return ResultVO.success("专业列表获取成功", majorsList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVO.fail("获取专业列表时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<List<Majors>> getMajorListByDepartment(String department) {
        try {
            // 参数校验
            if (department == null || department.isEmpty()) {
                return ResultVO.fail("学院名称不能为空");
            }
            // 构建查询条件
            QueryWrapper<Majors> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("department", department);

            // 执行查询
            List<Majors> majorsList = this.list(queryWrapper);

            if (majorsList.isEmpty()) {
                return ResultVO.success("未找到该学院下的专业", majorsList);
            }

            List<Majors> list = this.list(queryWrapper);
            int total= list.size();
            return ResultVO.success("专业列表获取成功", majorsList,total);
        } catch (Exception e) {
            log.error("按学院查询专业列表异常", e);
            return ResultVO.fail("查询专业列表时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<Majors> addMajor(Majors major) {
        try {
            // 检查专业名称是否已存在
            QueryWrapper<Majors> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("major", major.getMajor());
            if (this.getOne(queryWrapper) != null) {
                return ResultVO.fail("该专业名称已存在");
            }

            boolean saveSuccess = this.save(major);
            if (!saveSuccess) {
                return ResultVO.fail("专业添加失败");
            }
            return ResultVO.success("专业添加成功", major);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVO.fail("添加专业时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<Majors> updateMajor(Majors major) {
        try {
            QueryWrapper<Majors> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("major_id", major.getMajorId());
            Majors existingMajor = this.getOne(queryWrapper);

            if (existingMajor == null) {
                return ResultVO.fail("专业编号不存在");
            }
            // 检查新的专业名称是否已存在（排除当前专业自身）
            QueryWrapper<Majors> duplicateQuery = new QueryWrapper<>();
            duplicateQuery
                    .eq("major", major.getMajor() != null ? major.getMajor() : existingMajor.getMajor())
                    .eq("department", major.getDepartment() != null ? major.getDepartment() : existingMajor.getDepartment())
                    .ne("major_id", major.getMajorId()); // 排除当前专业

            if (this.getOne(duplicateQuery) != null) {
                return ResultVO.fail("该专业名称已存在");
            }

            // 检查专业是否有班级
            QueryWrapper<Classes> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("major",existingMajor.getMajor());
            List<Classes> classesList = classesMapper.selectList(queryWrapper1);
            if(!classesList.isEmpty()){
                return ResultVO.fail("该专业下有班级，不可以更新");
            }

            // 更新字段（只更新非空值）
            if (major.getMajor() != null) existingMajor.setMajor(major.getMajor());
            if (major.getDepartment() != null) existingMajor.setDepartment(major.getDepartment());

            boolean updateSuccess = this.updateById(existingMajor);
            if (!updateSuccess) {
                return ResultVO.fail("专业信息更新失败");
            }
            return ResultVO.success("专业信息更新成功", existingMajor);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVO.fail("更新专业时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<Majors> deleteMajor(String majorId) {
        try {
            QueryWrapper<Majors> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("major_id", majorId);
            Majors existingMajor = this.getOne(queryWrapper);

            if (existingMajor == null) {
                return ResultVO.fail("专业编号不存在");
            }

            // 检查专业是否有班级
            QueryWrapper<Classes> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("major",existingMajor.getMajor());
            List<Classes> classesList = classesMapper.selectList(queryWrapper1);
            if(!classesList.isEmpty()){
                return ResultVO.fail("该专业下有班级，不可以删除");
            }
            boolean deleteSuccess = this.removeById(majorId);
            if (!deleteSuccess) {
                return ResultVO.fail("专业删除失败");
            }
            return ResultVO.success("专业删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVO.fail("删除专业时发生异常：" + e.getMessage());
        }
    }
}
